package com.cherrypt.api.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cherrypt.api.common.enums.ResultEnum;
import com.cherrypt.api.common.exception.TipException;
import com.cherrypt.api.core.dao.TorrentDao;
import com.cherrypt.api.core.service.TorrentService;
import com.cherrypt.api.model.dataobject.Torrent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * @author intent
 * @date 2019/8/1 16:28
 * @about <link href='http://zzyitj.xyz/'/>
 */
@Service
public class TorrentServiceImpl extends ServiceImpl<TorrentDao, Torrent> implements TorrentService {
    private static final Logger logger = LoggerFactory.getLogger(TorrentServiceImpl.class);

    @Autowired
    private ValueOperations<String, Object> valueOperations;

    @Value("${api.config.redis.torrent.prefix}")
    private String torrentPrefix;

    @Value("${api.config.redis.torrent.exp}")
    private long torrentExp;

    @Override
    public Torrent getRedisTorrentByTid(int tid) {
        return (Torrent) valueOperations.get(torrentPrefix + tid);
    }

    @Override
    public void saveRedisTorrent(Torrent torrent) {
        valueOperations.set(torrentPrefix + torrent.getId(), torrent, Duration.ofSeconds(torrentExp));
    }

    @Override
    public Torrent getTorrentByTid(int tid) throws TipException {
        Torrent torrent = getRedisTorrentByTid(tid);
        if (torrent == null) {
            torrent = getById(tid);
            if (torrent == null) {
                throw new TipException(ResultEnum.NO_SUCH_SEED);
            }
            saveRedisTorrent(torrent);
            logger.info("缓存Torrent到Redis: {}", torrent);
        }
        return torrent;
    }

    @Override
    public Torrent getTorrentByHash(byte[] infoHash) {
        return this.getOne(new QueryWrapper<Torrent>().eq("info_hash", infoHash));
    }

    @Override
    public boolean existHash(byte[] infoHash) {
        return this.getOne(new QueryWrapper<Torrent>().eq("info_hash", infoHash)) == null;
    }

}
